package com.project.demo.util;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.project.demo.dao.UserFileMapper;
import com.project.demo.entity.UserFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;

/**
 * 审计定时任务
 */
@Component
public class AuditScheduled {
    private static int challengeSize = 5;// 挑战的块数量

    @Autowired
    UserFileMapper userFileMapper;

    @Scheduled(fixedDelay = 30000) // 任务执行完成后，延迟 3 秒执行下一次任务
    public void fixedDelayJob() {
        System.out.println("FixedDelayTask executed at: " + System.currentTimeMillis());
        LambdaQueryWrapper<UserFile> userFileLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userFileLambdaQueryWrapper.eq(UserFile::getStatus,0);
        List<UserFile> userFiles = userFileMapper.selectList(userFileLambdaQueryWrapper);
        userFiles.forEach(userFile -> {
            String fileBlock = userFile.getFileBlock();
            List<String> originalBlockHashes = Arrays.asList(fileBlock.split(","));
            int blockCount = originalBlockHashes.size();
            // 生成挑战
            List<Integer> challenge = PDPDataIntegrityVerification.generateChallenge(blockCount, challengeSize);
            File file = new File(userFile.getFilePath()); // 替换为实际文件路径
            try {
                List<String> currentBlockHashes = PDPDataIntegrityVerification.calculateBlockHashes(file);
                // 生成响应
                List<String> response = PDPDataIntegrityVerification.generateResponse(currentBlockHashes, challenge);
                System.out.println("响应：" + response);

                // 验证响应
                boolean isValid = PDPDataIntegrityVerification.verifyResponse(originalBlockHashes, currentBlockHashes, challenge, response);
                if (isValid) {
                    System.out.println("验证成功：数据完整且未被篡改。");
                } else {
                    userFile.setStatus(1);
                    userFileMapper.updateById(userFile);
                    System.out.println("验证失败：数据可能被篡改或损坏。");
                }
            } catch (Exception e) {
                userFile.setStatus(1);
                userFileMapper.updateById(userFile);
                System.out.println("验证失败：数据可能被篡改或损坏。");
                System.out.println(e);
            }
        });
    }
}
